// pages/my/index/index.js

const app = getApp();
const util = require('../../../utils/util');
const common = require('../../../utils/common');
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");
const timConst = require("../../../config/const");
import QRCode from '../../../utils/weapp-qrcode.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    cardInfo: {},
    userType: 2,
    hasCardInfo: false, // 是否有卡片信息
    hasGetPhoneNumber: false, // 是否已获取手机号
    visitedNum: 0, // 访问量
    todayVisitedNum: 0, // 今日访问量
    reInitToGetPhone: true, // 重置获取手机号
    hasNoMoreHistory: false, // 没有更多记录
    hasHistoryList: false, // 判断是否有历史记录
    fyNum: 1, // 页码
    fySize: 10, // 每页展示数
    historyList: [],
    firstTimeInIndex: true,
  },
  onShow: function () {
    util.hideShareMenu(); //隐藏转发按钮
    let _this = this;
    app.globalData.isHome = false;
    if (!app.globalData.hasCardInfoWithPhone) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.loginCallback = () => {
        _this.onShowCall();
      }
    } else {
      _this.onShowCall();
    }
    _this.setData({
        isXcxLogin: app.globalData.isXcxLogin
    })
  },

  onShowCall: function () {
    if (!app.globalData.hasGetPhoneNumber && !this.data.isXcxLogin) {
      this.showModal();
      return;
    }
    let userType = app.globalData.userType;
    let cardInfo = userType == 1 ? app.globalData.employeeInfo : userType == 2 ? app.globalData.customInfo : null;
    this.setData({
      userType: userType,
      cardInfo: cardInfo,
      hasCardInfo: app.globalData.hasCardInfo,
      hasGetPhoneNumber: app.globalData.hasGetPhoneNumber
    });
    // if (util.isNullOrEmpty(app.globalData.userSig) || util.isNullOrEmpty(app.globalData.adminSig)) {
    //   app.getUserSig();
    // }
    this.addUser();
    // this.addLocalWaitingVist();
    if (this.data.userType == 1) {
      this.getVisitedNum();
    } else {
      this.getHistoryList();
    }
    if(userType == 1){
        this.getEwm(api.urls.fsEwm + '?userType=1&id=' + app.globalData.employeeInfo.id);
    }
    
  },

  onShareAppMessage: function (o) {
    let _this = this;
    if (o.from) {
      return {
        title: "您好，这是我的名片。", //转发的标题
        path: '/pages/card/card?id=' + app.globalData.employeeInfo.id + '&userType=1'
      };
    }
  },

  /**
   * 添加当前员工到腾讯云平台【员工限定，顾客有别的方法】
   */
  addUser: async function () {
    if (app.globalData.userType == 2) {
      return;
    }
    if (app.globalData.adminSig == null) {
      return;
    }
    if (util.objIsNull(app.globalData.employeeInfo)) {
      return;
    }
    let random = parseInt(Math.random() * 10000);
    let url = 'https://console.tim.qq.com/v4/im_open_login_svc/account_import' + '?sdkappid=' + timConst.TimOptions.SDKAppID + '&identifier=admin' + '&usersig=' + app.globalData.adminSig + '&random=' + random + '&contenttype=json';
    let data;
    if (app.globalData.employeeInfo.headImgUrl) {
      data = {
        Identifier: 'E' + app.globalData.employeeInfo.id.toString(),
        Nick: app.globalData.employeeInfo.name,
        FaceUrl: app.globalData.employeeInfo.headImgUrl
      }
    } else {
      data = {
        Identifier: 'E' + app.globalData.employeeInfo.id.toString(),
        Nick: app.globalData.employeeInfo.name
      }
    }
    let res = await requestUtil.request("POST", url, data);
    if (res.data.ActionStatus == 'FAIL') {
      console.error('添加用户失败，ErrorCode：' + res.data.ErrorCode);
      console.error('ErrorInfo：' + res.data.ErrorInfo);
    } else {
      console.log('----------添加单个用户')
    }
  },

  /**
   * 跳转到编辑名片页面
   */
  toModify: function (e) {
    wx.navigateTo({
      url: '../../card-create-modify/card-cm?type=2'
    });
  },

  /**
   * 跳转到我的名片页面
   */
  toMyCard: function () {
    if (!this.data.hasGetPhoneNumber) {
      util.showToast('请先绑定手机号');
      return;
    }
    wx.navigateTo({
      url: '../../card/card?id=' + this.data.cardInfo.id + '&type=' + this.data.userType,
    })
  },

  /**
   * 历史记录
   */
  toHistory: function () {
    wx.navigateTo({
      url: '../../my/history/list'
    })
  },

  /**
   * 谁看过我
   */
  toWhoSeenMe: function (e) {
    let type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '../../my/who-seen-me/seen?type=' + type
    })
  },

  /**
   * 去聊天室
   */
  toChatRoom: function () {
    wx.navigateTo({
      url: '../../card-center/loginpage/login?userType=1',
    })
  },
  toQuestion: function() {
    wx.navigateTo({
      url: '../../question/center/center',
    })
  },
  /**
   * 创建名片
   */
  createCard: function () {
    wx.navigateTo({
      url: '../../card-create-modify/card-cm?type=1'
    })
  },

  /**
   * 修改头像
   */
  toChangeAvatar: function () {
    wx.navigateTo({
      url: '/pages/my/avatar-modify/avatar',
    })
  },

  /**
   * 获取被访问量
   */
  getVisitedNum: async function () {
    let res = await requestUtil.request("POST", api.urls.getHistoryTotal, {
      userId: this.data.cardInfo.id
    })
    if (res.data.code != 0) {
      util.showToast(res.data.msg, 'none');
      return;
    }
    let visitedList = res.data.data;
    for(let i in visitedList) {
        visitedList[i].totalTypeName = common.formatVisitType(visitedList[i].totalType);
    }
    this.setData({
        visitedList: visitedList,
    })
  },

  /**
   * 获取历史记录列表
   */
  getHistoryList: async function () {
    let params = {
        fyNum: this.data.fyNum,
        fySize: this.data.fySize,
    };
    let url;
    // 未登录时用缓存中的数据
    if (!this.data.hasGetPhoneNumber) {
      let userIds = wx.getStorageSync('userIds').split(',');
      if (util.isNullOrEmpty(userIds)) {
        this.setData({
          hasHistoryList: false
        })
        return;
      }
      params.userIds = userIds;
      url = api.urls.getCompanyUserList;
    } else {
      // 登录后查客户id
      params.custId = this.data.cardInfo.id;
      url = api.urls.getDistinctHistoryList;
    }
    let res = await requestUtil.request("POST", url, params);
    if (res.data.code != 0) {
      util.showToast(res.data.msg);
      return;
    }
    let historyList = res.data.data.rows;
    let formatList = [];
    let formatIdsArr = [];
    // 格式化日期和头像地址
    for (let i = 0; i < historyList.length; i++) {
      if (!this.data.hasGetPhoneNumber) {
        //TODO 这个时间不应该是当前时间吧？应该要改
        let arr = util.formatChineseDate(new Date()).split('-');
        let time = {
          year: arr[0],
          month: arr[1],
          day: arr[2]
        }
        formatList.push({
          id: historyList[i].id,
          visitedDate: time,
          name: historyList[i].name,
          headImgUrl: historyList[i].headImgUrl ? api.picUrl + historyList[i].headImgUrl : null,
          companyName: historyList[i].companyName,
        })
        formatIdsArr.push(historyList[i].id);
      } else {
        let arr = util.formatChineseDate(new Date(historyList[i].createTime.replace(/-/g, '/'))).split('-');
        let time = {
          year: arr[0],
          month: arr[1],
          day: arr[2]
        }
        formatList.push({
          id: historyList[i].userId,
          visitedDate: time,
          headImgUrl: historyList[i].employeeHeadImgUrl ? api.picUrl + historyList[i].employeeHeadImgUrl : null,
          name: historyList[i].employeeName,
          companyName: historyList[i].employeeCompanyName
        })
        formatIdsArr.push(historyList[i].userId);
      }
    }
    let list = this.data.historyList;
    let historyListIdsArr = list.map(x => x.id);
    for (let j = 0; j < formatIdsArr.length; j++) {
      if (historyListIdsArr.indexOf(formatIdsArr[j]) == -1) {
        list.push(formatList[j])
      }
    }
    let hasNoMore = true;
    if(params.fyNum * params.fySize < res.data.data.total) {
        hasNoMore = false;
    }
    if (this.data.hasGetPhoneNumber) {
      this.changeTempHistoryList(formatIdsArr);
    }
    this.setData({
      historyList: list,
      hasHistoryList: true,
      hasNoMoreHistory: hasNoMore
    })
  },

  /**
   * 修改缓存
   */
  changeTempHistoryList: function (list) {
    if (list && list.length > 0) {
      wx.setStorageSync('userIds', list.toString());
    }
  },

  /**
   * 显示获取手机modal
   */
  showModal: function () {
    this.setData({
      modalName: 'GetPhoneModal'
    });
  },

  /**
   * 拒绝获取手机
   */
  rejectModal: function () {
    this.setData({
      cardInfo: {},
      reInitToGetPhone: true,
      hasCardInfo: false,
      hasGetPhoneNumber: false
    });
    app.globalData.hasGetPhoneNumber = false;
    this.getHistoryList();
    this.hideModal();
  },

  /**
   * 隐藏modal
   */
  hideModal: function () {
    this.setData({
      modalName: ''
    });
  },

  /**
   * 获取用户手机号
   */
  getPhoneNumber: async function (e) {
    if (e.detail.errMsg.includes('user deny')) {
      wx.showToast({
        title: '请先使用手机号绑定微信',
        icon: 'none'
      });
      return;
    };
    let _this = this;
    let params = {};
    let sessionKey = wx.getStorageSync('session_key')
    params.sessionkey = sessionKey;
    params.ivdata = e.detail.iv;
    params.encrypdata = e.detail.encryptedData;
    if (util.isNullOrEmpty(sessionKey)) {
      this.reLogin(params, "getPhone");
      return;
    }
    // 首次获取手机号
    if (this.data.reInitToGetPhone) {
      wx.checkSession({
        success: () => {
          _this.getPhone(params);
        },
        fail: () => {
          // session_key过期就重新获取
          _this.reLogin(params, "getPhone");
        }
      })
    } else {
      this.reLogin(params, "getPhone");
    }
  },

  /**
   * 获取手机号
   */
  getPhone: async function (params) {
    let _this = this;
    let res = await requestUtil.request("POST", api.urls.getPhone, params);
    if (!res.data) {
      wx.showToast({
        title: '无法获取信息，请重试。',
        icon: 'none'
      })
      _this.setData({
        reInitToGetPhone: false,
      })
      return;
    }
    let phone = res.data.purePhoneNumber; // 没有区号的手机号
    this.bindUser(phone);
  },

  /**
   * openid绑定用户
   */
  bindUser: async function (phone) {
    let openid = wx.getStorageSync('openid');
    if (!openid) {
      this.reLogin(phone, "bindUser");
      return;
    }
    let params = {
      xcxOpenid: openid,
      mobile: phone
    }
    let bindRes = await requestUtil.request("POST", api.urls.bindEmployee, params);
    if (bindRes.data.code != 0) {
      util.showToast(bindRes.data.msg, 'none');
      return;
    }
    util.showToast('绑定成功', 'success');
    app.globalData.phone = phone;
    app.onShow();
    this.onShow();
    this.hideModal();
  },

  /**
   * login重新获取session_key
   */
  reLogin: function (params, type) {
    let _this = this;
    wx.login({
      success: async function (res) {
        let init = await requestUtil.request("POST", api.urls.initUserInfo, {
          code: res.code
        });
        wx.setStorage({
          key: 'openid',
          data: init.data.data.openid
        });
        wx.setStorage({
          key: "session_key",
          data: init.data.data.session_key
        });
        if (type == "getPhone") {
          params.sessionkey = init.data.data.session_key;
          _this.getPhone(params);
        } else if (type == "bindUser") {
          _this.bindUser(params);
        }
      }
    })
  },

  /**
   * 点击查看更多
   */
  moreDetail: function (e) {
    let id = e.currentTarget.dataset.id;
    // 固定，历史记录页面，顾客可查看员工信息
    wx.navigateTo({
      url: '../../card/card?id=' + id + '&type=' + 1,
    })
  },
  toMyCustomer: function(){
    wx.navigateTo({
      url: '../../my/my-customer/my-customer',
    })
  },
  showModal2(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  getEwm(api){
    new QRCode('myQrcode',{
        text: api,
        width: 160,
        height: 160,
        colorDark: '#2196F3',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
        callback: (res) => {
          console.log(res.path)
        }
    })
  },

})